package com.kzd.sdk.callback;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.kzd.sdk.entity.KZD_BaseResponseList;
import com.kzd.sdk.error.KZD_CustomException;
import com.kzd.sdk.utils.ExceptionUtils;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

public abstract class KZD_JsonCallbackList<E> extends AbsCallback<KZD_BaseResponseList<E>> {

    private final Class<E> eClass;

    public KZD_JsonCallbackList(Class<E> eClass) {
        this.eClass = eClass;
    }

    @Override
    public KZD_BaseResponseList<E> convertResponse(okhttp3.Response response) throws Throwable {
        ResponseBody body = response.body();
        if (body == null)
            throw new KZD_CustomException("body is null", 1000);
        String bodyStr = body.string();
        if (bodyStr == null || bodyStr.length() == 0)
            throw new KZD_CustomException("body is null", 1000);
        Gson mGson = new Gson();
        KZD_BaseResponseList<E> responseList = mGson
                .fromJson(bodyStr, new TypeToken<KZD_BaseResponseList<E>>() {
                }.getType());
        List<E> list = new ArrayList<E>();
        if (responseList.getCode() == 1) {
            String jsonString = mGson.toJson(responseList.getData());
            JsonArray array = new JsonParser().parse(jsonString).getAsJsonArray();
            for (final JsonElement elem : array) {
                list.add(mGson.fromJson(elem, eClass));
            }
        } else {
            throw new KZD_CustomException(responseList.getMessage(), responseList.getCode());
        }
        responseList.setData(list);

        return responseList;
    }

    @Override
    public void onStart(Request<KZD_BaseResponseList<E>, ? extends Request> request) {
        super.onStart(request);
        onStart();
    }

    @Override
    public void onSuccess(Response<KZD_BaseResponseList<E>> response) {
        List<E> data = response.body().getData();
        if (data == null) {
            return;
        }
        onSuccess(data);
    }

    @Override
    public void onError(Response<KZD_BaseResponseList<E>> response) {
        super.onError(response);
        onError(ExceptionUtils.getMessage(response.getException()));
    }

    public void onStart() {
    }

    public void onSuccess(List<E> data) {

    }

    public void onError(String message) {

    }
}
